<!-- src/views/UserManagement.vue -->
<template>
  <div class="p-6">
    <!-- 搜索 & 筛选 -->
    <a-space class="mb-4">
      <a-input v-model:value="filters.keyword" placeholder="搜索用户名/邮箱" style="width: 250px" />
      <a-select v-model:value="filters.role" placeholder="全部角色" style="width: 150px" allow-clear>
        <a-select-option v-for="role in roles" :key="role" :value="role">{{ role }}</a-select-option>
      </a-select>
      <a-select v-model:value="filters.emailConfirmed" placeholder="全部邮箱激活状态" style="width: 120px" allow-clear>
        <a-select-option value="active">已激活</a-select-option>
        <a-select-option value="disabled">未激活</a-select-option>
      </a-select>
      <a-button type="primary" @click="fetchUsers">搜索</a-button>
    </a-space>



    <!-- 用户表格 -->
    <a-table :columns="columns" :data-source="filteredUsers" row-key="userId" :row-selection="rowSelection" bordered
      :rowClassName="rowClassName">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'emailConfirmed'">
          <a-tag :color="record.emailConfirmed==='active' ? 'green' : 'red'">
            {{ record.emailConfirmed==='active' ? '已激活' : '未激活' }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'action'">
          <a-space>

            <a-button type="link" @click.stop="openDetails(record)">详情</a-button>
            <a-button type="link" @click.stop="openAssignRoles(record)">分配角色</a-button>
          </a-space>
        </template>

        <template v-else-if="column.key === 'roles'">
          {{ record.roles.join(', ') }}
        </template>

        <template v-else-if="column.key === 'createdAt'">
          {{ dayjs(record.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <template v-else>
          {{ record[column.dataIndex] }}
        </template>
      </template>
    </a-table>

    <!-- 用户详情侧边栏 -->
    <a-drawer title="用户详情" :visible="showDetails" :width="360" @close="showDetails = false" placement="right">
      <div v-if="selectedUser">
        <p><strong>用户名：</strong> {{ selectedUser.userName }}</p>
        <p><strong>邮箱：</strong> {{ selectedUser.email }}</p>
        <p><strong>角色：</strong> {{ selectedUser.roles.join(', ') }}</p>
        <p><strong>状态：</strong>
          <a-tag :color="selectedUser.emailConfirmed==='active' ? 'green' : 'red'">
            {{ selectedUser.emailConfirmed==='active' ? '已激活' : '未激活' }}
          </a-tag>
        </p>
        <p><strong>注册时间：</strong> {{ dayjs(selectedUser.createdAt).format('YYYY-MM-DD HH:mm:ss') }}</p>
      </div>
    </a-drawer>


    <!-- 分配角色抽屉 -->
    <a-drawer title="分配角色" :visible="showAssignDrawer" :width="400" @close="closeAssignDrawer" placement="right">
      <div v-if="selectedUser">
        <p><strong>用户名：</strong>{{ selectedUser.userName }}</p>
        <p><strong>邮箱：</strong>{{ selectedUser.email }}</p>

        <a-form layout="vertical">
          <a-form-item label="选择角色">
            <a-select v-model:value="selectedRoles" mode="multiple" placeholder="请选择角色" style="width: 100%">
              <a-select-option v-for="role in roles" :key="role" :value="role">
                {{ role }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>

        <div style="text-align: right; margin-top: 16px">
          <a-button style="margin-right: 8px" @click="closeAssignDrawer">取消</a-button>
          <a-button type="primary" @click="saveRoles">保存</a-button>
        </div>
      </div>
    </a-drawer>


  </div>
</template>




<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { apiFetch } from '@/utils/request'  // 引入工具函数
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
const identityurl = import.meta.env.VITE_API_IDENTITY

// 用户模型
interface User {
  userId: string
  userName: string
  email: string
  roles: string[]
  emailConfirmed: string
  createdAt: string
}

interface Filters {
  keyword: string
  role: string
  emailConfirmed: string
}

interface ApiResponse<T> {
  isSuccess: boolean
  errors: string[]
  data: T
}


// 响应式数据
const users = ref<User[]>([])
const roles = ref<string[]>([])
const filters = ref<Filters>({ keyword: '', role: '', emailConfirmed: '' })

// 生命周期钩子里获取数据
onMounted(async () => {
  await fetchUsers()
})

async function fetchUsers() {
  try {
    const query = new URLSearchParams(
      Object.entries(filters.value).reduce((acc, [key, value]) => {
        acc[key] = String(value)
        return acc
      }, {} as Record<string, string>)
    )

    const response = await apiFetch<ApiResponse<{userId:string,userName:string,email:string,roles:string[],emailConfirmed:boolean,createdAt:string}[]>>(
      `${identityurl}/api/account/all-user-accounts?${query.toString()}`
    )
    users.value = response.data.map(a=>({
      userId:a.userId,
      userName:a.userName,
      email:a.email,
      roles:a.roles,
      emailConfirmed:a.emailConfirmed?'active':'disabled',
      createdAt:a.createdAt
    }))
    roles.value = [...new Set(users.value.flatMap(u => u.roles))]
  } catch (err) {
    console.error('获取用户失败', err)
  }
}

// 选中用户
const selectedUsers = ref<string[]>([]) // 存储用户 id
const showDetails = ref(false)
const selectedUser = ref<User | null>(null)

// 表格列
interface Column {
  title: string
  dataIndex?: keyof User | string
  key: string
}
const columns: Column[] = [
  { title: '用户名', dataIndex: 'userName', key: 'userName' },
  { title: '邮箱', dataIndex: 'email', key: 'email' },
  { title: '角色', dataIndex: 'roles', key: 'roles' },
  { title: '邮箱激活状态', dataIndex: 'emailConfirmed', key: 'emailConfirmed' },
  { title: '注册时间', dataIndex: 'createdAt', key: 'createdAt' },
  { title: '操作', key: 'action' }
]

// 过滤后的用户
const filteredUsers = computed<User[]>(() => {
  return users.value.filter(u => {
    const matchKeyword =
      !filters.value.keyword ||
      u.userName.includes(filters.value.keyword) ||
      u.email.includes(filters.value.keyword)
    const matchRole = !filters.value.role || u.roles.includes(filters.value.role)
    const matchStatus = !filters.value.emailConfirmed || u.emailConfirmed === filters.value.emailConfirmed
    return matchKeyword && matchRole && matchStatus
  })
})

const rowSelection = computed(() => ({
  selectedRowKeys: selectedUsers.value,
  onChange: (keys: string[]) => {
    selectedUsers.value = keys
  }
}))

// 打开详情
function openDetails(user: User) {
  selectedUser.value = user
  showDetails.value = true
}


const rowClassName = (_: User, index: number) => {
  return index % 2 === 1 ? 'table-row-light' : 'table-row-dark'
}



const showAssignDrawer = ref(false)
const selectedRoles = ref<string[]>([])

// 打开分配角色抽屉
function openAssignRoles(user: User) {
  selectedUser.value = user
  selectedRoles.value = [...user.roles] // 初始化选中已有的角色
  showAssignDrawer.value = true
}

// 关闭抽屉
function closeAssignDrawer() {
  showAssignDrawer.value = false
  selectedUser.value = null
  selectedRoles.value = []
}

// 保存分配角色
async function saveRoles() {
  if (!selectedUser.value) return
  try {
    // 调用后端 API 更新角色
    await apiFetch(`${identityurl}/api/account/assign-roles`, {
      method: 'POST',
      body: JSON.stringify({
        userId: selectedUser.value.userId,
        roles: selectedRoles.value
      })
    })

    // 本地同步更新
    selectedUser.value.roles = [...selectedRoles.value]

    message.success('角色分配成功')
    closeAssignDrawer()
  } catch (err) {
    console.error('角色分配失败', err)
    message.error('角色分配失败')
  }
}
</script>

<style scoped>
/* 交错行背景 */
:deep(.ant-table-tbody > tr.table-row-light > td) {
  background-color: #f5f5f5;
  /* 浅灰色 */
}

:deep(.ant-table-tbody > tr.table-row-dark > td) {
  background-color: #ffffff;
  /* 白色 */
}

/* 鼠标悬停高亮 */
:deep(.ant-table-tbody > tr:hover > td) {
  background: #e6f7ff !important;
}
</style>
